package dormouse.vfs.metadata;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.MemoryCacheImageInputStream;

import org.apache.commons.vfs2.FileObject;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


/**
 * This file reads the metadata from an image and returns the values in map.
 * 
 * @author Mark
 * 
 */
public class ImageMetadataReader extends AbstractMetaDataReader implements
		IMetadataReader {

	public ImageMetadataReader() {
		setFileExtensions(
				new String[] { "jpg", "jpeg", "png", "gif", "tif", "tiff",
						"bmp" });
	}

	@Override
	public Map<String, String> getMetadata(FileObject file) throws IOException {

		String ext = file.getName().getExtension();
		ext = (ext.equalsIgnoreCase("tiff"))?"tif":ext;
		Iterator<ImageReader> it = ImageIO.getImageReadersBySuffix(ext);
		if (it.hasNext()) {
			ImageReader reader = (ImageReader) it.next();
			ImageInputStream iis = new MemoryCacheImageInputStream(file.getContent().getInputStream());
			reader.setInput(iis);
			IIOMetadata iiometadata = reader.getImageMetadata(0);

			String[] formatNames = iiometadata.getMetadataFormatNames();
			processMetaData(iiometadata, formatNames);

			formatNames = iiometadata.getExtraMetadataFormatNames();
			processMetaData(iiometadata, formatNames);
			
			formatNames = new String[]{iiometadata.getNativeMetadataFormatName()};
			processMetaData(iiometadata, formatNames);
			
			iis.close();
			
		}
		return this.metadata;
	}

	private void processMetaData(IIOMetadata iiometadata, String[] formatNames) {
		if (formatNames != null) {
			for (int i = 0; i < formatNames.length; i++) {
				Node n = iiometadata.getAsTree(formatNames[i]);
				getNodes(n);
			}
		}
	}

	private void getNodes(Node node) {
		NodeList nl = node.getChildNodes();
		int numNodes = nl.getLength();
		Node currNode = null;
		Node val = null;
		String name = null;
		String value = null;
		for (int i = 0; i < numNodes; i++) {
			currNode = nl.item(i);
			if (currNode != null) {
				name = currNode.getNodeName();
				val = currNode.getAttributes().getNamedItem("value");
				value = (val != null) ? val.getNodeValue() : "";
				this.metadata.put(name, value);
				getNodes(currNode);
			}
		}
	}

}
